import EventCenter from "../TFrame/script/helper/EventCenter"
import SingletonBase from "../TFrame/script/helper/SingleTonBase"
import EventNames from "./EventNames"
import FireBaseAPI from "./FireBaseAPI"
import NativeCaller from "./NativeCaller"
import { ActionType } from "./net/Enum"
import ServiceLogic from "./net/ServerLogic"
import ResManager from "./ResManager"
import CoinSystem from "./system/CoinSystem"

export default class PlayerDataMgr extends SingletonBase {

    //广告录屏开关
    static isADVideo = false
    //关卡最高奖牌
    key_level_medal = "key_level_medal"
    level_medal_json = {}

    //一个星星一分，关卡可重复玩重复计
    key_total_score = "key_total_score"
    totalScore = 0;

    key_music_on = "key_music_on"
    music_on = 1;
    key_effect_on = "key_effect_on";
    effect_on = 1;

    //提示拥有数量
    key_tips_owned = "key_tips_owned"
    tipsOwned = 0;

    key_tutorial_played = "key_tutorial_played";
    turotial_played = 0;

    //过的关卡数
    key_passed_level_cnt = "key_passed_level_cnt"
    passed_level_cnt = 0;

    //每5关领一个金币奖
    key_level_pass_reward_idx = "key_level_pass_reward_idx"
    level_pass_reward_idx = 0; 

    key_last_version = "key_last_version"
    str_last_version = ""

    key_totalAdRevenue = "key_totalAdRevenue"
    totalAdRevenue = 0;

    key_notShowFullLevelCount = "notShowFullLevelCount";
    notShowFullLevelCount = 0;

    autoPlay = false;

    getItemWithDefault(key: string, value) {
        let pv = cc.sys.localStorage.getItem(key)
        if (pv == null || pv.length == 0) {
            pv = value
        }
        return pv
    }


    key_is_register = 'key_is_register'
    private _is_register = '1'
    public get is_register() {
        return this._is_register
    }
    public set is_register(v) {
        this._is_register = v
        cc.sys.localStorage.setItem(this.key_is_register, this._is_register)
        cc.log("persisit is register:%s", this._is_register)
    }



    //当前关卡数据
    //关卡序号(用于关卡选择和关卡显示)
    lastLevelIndex = 0
    key_lastLevelIndex = "lastLevelIndex"

    setLastLevelIndex(i) {
        this.lastLevelIndex = i
        cc.sys.localStorage.setItem(this.key_lastLevelIndex, i)
    }
    getLastLevelIndex() {
        return this.lastLevelIndex
    }

    loadDataFromPersistence() {
        this.lastLevelIndex = parseInt(this.getItemWithDefault(this.key_lastLevelIndex, -1))
        this.totalScore = parseInt(this.getItemWithDefault(this.key_total_score, 0))

        this.music_on = parseInt(this.getItemWithDefault(this.key_music_on, 1));
        this.effect_on = parseInt(this.getItemWithDefault(this.key_effect_on, 1));
        this.switchMusic(this.music_on);
        this.switchEffect(this.effect_on);

        let level_medal_str = cc.sys.localStorage.getItem(this.key_level_medal)
        if (level_medal_str) {
            this.level_medal_json = JSON.parse(level_medal_str)
        }

        this.tipsOwned = parseInt(this.getItemWithDefault(this.key_tips_owned, 1));
        this.turotial_played = parseInt(this.getItemWithDefault(this.key_tutorial_played, 0))
        this._is_register = this.getItemWithDefault(this.key_is_register, null)
        console.log("PlayerDataMgr loadDataFromPersistence _is_register:", this._is_register)
        console.log(`PlayerDataMgr tipsOwned:${this.tipsOwned}`)

        this.passed_level_cnt = parseInt(this.getItemWithDefault(this.key_passed_level_cnt, 0));
        this.level_pass_reward_idx = parseInt(this.getItemWithDefault(this.key_level_pass_reward_idx, 0));
        this.str_last_version = this.getItemWithDefault(this.key_last_version, "")
        this.checkVersion();

        this.totalAdRevenue = parseInt(this.getItemWithDefault(this.key_totalAdRevenue, 0));
        
        this.notShowFullLevelCount = parseInt(this.getItemWithDefault(this.key_notShowFullLevelCount, 0));
    }

    checkVersion() {
        let nowVer:string =  NativeCaller.getVersionName()
        if(this.str_last_version.length == 0 ||
            (this.str_last_version.length > 0 && nowVer != null && nowVer != this.str_last_version)) {
            cc.sys.localStorage.setItem(this.key_last_version, nowVer);
            ServiceLogic.action(ActionType.ActionUpgradeApp, {"beiz": this.str_last_version || "未知"});
            return
        }
    }

    persist() {
        let level_medal_str = JSON.stringify(this.level_medal_json)
        cc.sys.localStorage.setItem(this.key_level_medal, level_medal_str)
        cc.sys.localStorage.setItem(this.key_effect_on, this.effect_on)
        cc.sys.localStorage.setItem(this.key_level_pass_reward_idx, this.level_pass_reward_idx);
        cc.sys.localStorage.setItem(this.key_notShowFullLevelCount, this.notShowFullLevelCount);
    }

    updateLevelStar(lv: number, star: number) {
        let resName = ResManager.getLevelResNameByIndex(lv);
        let old = this.level_medal_json[resName]
        // cc.log(`updateLevelStar old:${old} rank:${star}`)
        if (old != null) {
            if (old < star) {
                this.level_medal_json[resName] = star
            }
        } else {
            this.level_medal_json[resName] = star
        }
        this.persist()
    }

    getLevelStar(lv: number) {
        let resName = ResManager.getLevelResNameByIndex(lv);
        let star = this.level_medal_json[resName]
        return star || 0
    }


    addScore(score: number) {
        this.totalScore += score;
        cc.sys.localStorage.setItem(this.key_total_score, this.totalScore);
        NativeCaller.leaderboardSubmitScore(this.totalScore);
    }

    passLevel() {
        this.passed_level_cnt++;
        cc.sys.localStorage.setItem(this.key_passed_level_cnt, this.passed_level_cnt);

        this.level_pass_reward_idx += 1;
        this.persistLevelPassRewardIdx();

        if (this.passed_level_cnt == 2) {
            // FireBaseAPI.logEvent("play_cnt_2", {});
        } else if (this.passed_level_cnt == 4) {
            // FireBaseAPI.logEvent("play_cnt_4", {});
        } else if (this.passed_level_cnt == 6) {
            FireBaseAPI.logEvent("play_cnt_6", {});
        } else if (this.passed_level_cnt == 10) {
            FireBaseAPI.logEvent("play_cnt_10", {});
        } else if (this.passed_level_cnt == 20) {
            FireBaseAPI.logEvent("play_cnt_20", {});
        } else if (this.passed_level_cnt == 50) {
            FireBaseAPI.logEvent("play_cnt_50", {});
        } else if (this.passed_level_cnt == 100) {
            FireBaseAPI.logEvent("play_cnt_100", {});
        }
    }

    persistLevelPassRewardIdx() {
        cc.sys.localStorage.setItem(this.key_level_pass_reward_idx, this.level_pass_reward_idx);
    }

    switchMusic(on: number) {
        console.log(`switchMusic this.music_on:${this.music_on}, on:${on}`);
        if (this.music_on != on) {
            this.music_on = on;
            cc.sys.localStorage.setItem(this.key_music_on, this.music_on)
        }
        cc.audioEngine.setMusicVolume(on ? 1.0 : 0);
    }

    switchEffect(on: number) {
        if (this.effect_on != on) {
            this.effect_on = on;
            cc.sys.localStorage.setItem(this.key_effect_on, this.effect_on)
            console.log(`switchEffect ${this.music_on}, ${cc.sys.localStorage.getItem(this.key_effect_on)}`);
        }
        cc.audioEngine.setEffectsVolume(on ? 1.0 : 0);
    }

    consumeTip(n: number = 1): boolean {
        if (this.tipsOwned < n)
            return false;
        this.tipsOwned -= n;
        cc.sys.localStorage.setItem(this.key_tips_owned, this.tipsOwned)
        EventCenter.emit(EventNames.TipChangedDec)
        FireBaseAPI.logEvent("tip_use", {});
        return true;
    }

    consumeCoinTip(coin: number = 100): boolean {
        if (CoinSystem.cosumeCoin(coin)) {
            FireBaseAPI.logEvent("Event_tip_use", { "coinhave": CoinSystem.coinInMomory });
            return true;
        }
        return false;
    }

    addTips(n: number): void {
        this.tipsOwned += n;
        cc.sys.localStorage.setItem(this.key_tips_owned, this.tipsOwned)
        EventCenter.emit(EventNames.TipChangedADD)
    }

    tutorialDone() {
        this.turotial_played = 1;
        cc.sys.localStorage.setItem(this.key_tutorial_played, this.turotial_played);
        ServiceLogic.action(ActionType.ActionNewHandDone, {});
        FireBaseAPI.logEvent("tutorial_done", {});
    }

    addAdRevenue(value:number) {
        this.totalAdRevenue += value;
        cc.sys.localStorage.setItem(this.key_totalAdRevenue, this.totalAdRevenue)
    }
}
